//
//  HRFunChatFromSelfViewController.m
//  Hear
//
//  Created by mac on 2017/11/24.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "HRFunChatFromSelfViewController.h"
#import "HRFunChatSelfCell.h"
#import "TableViewAnimationKitHeaders.h"
#import "MJRefresh.h"
#import "HRFunChatViewModel.h"
#import "HRFunChatModel.h"
#import "EaseMessageViewController.h"
#import "HRPostSoundViewModel.h"
@interface HRFunChatFromSelfViewController ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic, strong)NSMutableArray *contentArray;
@property(nonatomic, strong)HRFunChatViewModel *viewModel;
@property (nonatomic, assign)NSInteger pIndex;
@property(nonatomic, strong)HRFunChatModel *lastFunModel;
@property(nonatomic, strong)HRFunChatSelfCell *currentCell;
@property(nonatomic, strong)HRPostSoundViewModel *saveSoundModel;

@property (nonatomic, strong) NSMutableDictionary *param;

@end

static BOOL isHeader = YES;

@implementation HRFunChatFromSelfViewController

- (NSMutableDictionary *)param {
    if (!_param) {
        _param = [NSMutableDictionary dictionary];
    }
    return _param;
}

#pragma mark - Get and Set
- (HRFunChatViewModel *)viewModel{
    if (_viewModel == nil) {
        _viewModel = [[HRFunChatViewModel alloc] init];
    }
    return _viewModel;
}

- (HRPostSoundViewModel *)saveSoundModel{
    if (_saveSoundModel == nil) {
        _saveSoundModel = [[HRPostSoundViewModel alloc] init];
    }
    return _saveSoundModel;
}

- (NSMutableArray *)contentArray{
    if (_contentArray == nil) {
        _contentArray = [[NSMutableArray alloc] init];
    }
    return _contentArray;
}
- (UITableView *)tableView{
    if (_tableView == nil) {
        _tableView = [UITableView new];
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.frame = self.view.bounds;
        _tableView.rowHeight = 80;
        _tableView.height = self.view.height-kStatusBarHeight*2-30-kTabBarHeight-kStatusBarHeight;
        DDLog(@"%f",_tableView.height);
    }
    return _tableView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
//    [[NSUserDefaults standardUserDefaults] setInteger:0 forKey:@"cacheTime"];
    
    [self.view addSubview:self.tableView];
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        self.tableView.estimatedRowHeight = 0;
    }
    [self getFunChatContent];
//    [self creatDefaultParam];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadChatSelfNotifi) name:@"reloadChatSelfNotifi" object:nil];
}


#pragma mark - UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.contentArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HRFunChatSelfCell *cell = [HRFunChatSelfCell cellWithTableView:tableView];
    cell.chatModel = self.contentArray[indexPath.row];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    WeakSelf
    cell.playMedioBlock = ^(HRFunChatModel *model) {
        if (model || self.lastFunModel){
            dispatch_async(dispatch_get_main_queue(), ^{
                if(![model.LocalId isEqualToString:self.lastFunModel.LocalId]){
                    weakSelf.lastFunModel.isPlaying = NO;
                }
                [weakSelf.tableView reloadData];
                if (weakSelf.contentArray.count < 20){
                    weakSelf.tableView.mj_footer.hidden = YES;
                }
                weakSelf.lastFunModel = model;
                weakSelf.currentCell = cell;
            });
        }
    };
    return cell;
}




-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    HRFunChatModel *model = self.contentArray[indexPath.row];
    if ([model.UserLocalId isEqualToString:USERID]){
        [MBProgressHUD showMessage:@"当前为自己的话题" finishBlock:nil];
        return;
    }
    if (model.isPlaying){
        [self.currentCell playSound];
    }
    [MobClick event:@"Hearer5"];

    if (!model.isSender){
        EMTextMessageBody *body = [[EMTextMessageBody alloc] initWithText:model.TopicTitle];
        NSString *from = [[EMClient sharedClient] currentUsername];
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[@"isFromFunChat"] = @"1";
        dict[@"nickName"] = NICKNAME;
        dict[@"icon"] = ICONNAME;
        dict[@"iconColor"] = ICONCOLOR;
        dict[@"otherNickName"] = model.NickName;
        dict[@"otherIcon"] = model.UserPictureName;
        dict[@"SoundUrl"] = model.SoundUrl;
        dict[@"SoundLength"] = model.SoundLength;
        EMMessage *message = [[EMMessage alloc] initWithConversationID:model.UserLocalId from:USERID to:model.UserLocalId  body:body ext:dict];
        message.chatType = EMChatTypeChat;
    [[EMClient sharedClient].chatManager sendMessage:message progress:nil completion:^(EMMessage *message, EMError *error) {
        if (!error){
            model.isSender = YES;
            dispatch_async(dispatch_get_main_queue(), ^{
                EaseMessageViewController *messgaeVC = [[EaseMessageViewController alloc] initWithConversationChatter:model.UserLocalId conversationType:EMConversationTypeChat];
                messgaeVC.otherNickNameStr = model.NickName;
                messgaeVC.otherIconName = model.UserPictureName;
                messgaeVC.title = model.NickName;
//                messgaeVC.isFromChatSelf = YES;
//                messgaeVC.TopicTitle = model.TopicTitle;
//                messgaeVC.soundUrl = model.SoundUrl;
//                messgaeVC.soundLenght = model.SoundLength;
                [self.navigationController pushViewController:messgaeVC animated:YES];
            });
        }
    }];
        return;
    }
    EaseMessageViewController *messgaeVC = [[EaseMessageViewController alloc] initWithConversationChatter:model.UserLocalId conversationType:EMConversationTypeChat];
    messgaeVC.otherNickNameStr = model.NickName;
    messgaeVC.otherIconName = model.UserPictureName;
    messgaeVC.title = model.NickName;
//    messgaeVC.isFromChatSelf = YES;
//    messgaeVC.TopicTitle = model.TopicTitle;
//    messgaeVC.soundUrl = model.SoundUrl;
//    messgaeVC.soundLenght = model.SoundLength;
    [self.navigationController pushViewController:messgaeVC animated:YES];
}

-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    HRFunChatModel *model = self.contentArray[indexPath.row];
    if ([model.UserLocalId isEqualToString:USERID]){
        return YES;
    }
    return NO;

}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        HRFunChatModel *model = self.contentArray[indexPath.row];
        [self deleteUserTopic:model andCurrentIndex:indexPath.row];
    }
}

- (void)deleteUserTopic:(HRFunChatModel *)model andCurrentIndex:(NSUInteger)index{
    NSMutableDictionary *paramDict = [NSMutableDictionary dictionary];
    paramDict[@"UserTopicLocalId"] = model.LocalId;
    paramDict[@"UserLocalId"] = USERID;
    WeakSelf
    [self.saveSoundModel deleteUserTopic:paramDict isSeccess:^(BOOL isSeccess) {
        if (isSeccess){
            [MBProgressHUD showMessage:@"已删除" finishBlock:nil];
            [weakSelf.contentArray removeObjectAtIndex:index];
            [weakSelf.tableView deleteRow:index inSection:0 withRowAnimation:UITableViewRowAnimationRight];
            [weakSelf.tableView reloadData];
            if (weakSelf.contentArray.count < 20){
                weakSelf.tableView.mj_footer.hidden = YES;
            }
            
        }
    }];
}

- (void)starAnimationWithTableView:(UITableView *)tableView {
    
    [TableViewAnimationKit showWithAnimationType:4 tableView:tableView];
}


- (void)getFunChatContent{
    self.pIndex = 0;
    
    [self getFunChatData:YES];
    WeakSelf
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.pIndex = 0;
        [self getFunChatData:YES];
        [weakSelf.tableView.mj_header endRefreshing];
    }];
    
    //    //上拉加载
    self.tableView.mj_footer=[MJRefreshAutoStateFooter footerWithRefreshingBlock:^{
        weakSelf.pIndex ++;
        [weakSelf getFunChatData:NO];
        [weakSelf.tableView.mj_footer endRefreshing];
    }];
}

- (void)getFunChatData:(BOOL)isHead{
    NSMutableDictionary *paramDict = [NSMutableDictionary dictionary];
    paramDict[@"PageSize"] = @"20";
    paramDict[@"PageIndex"] = [NSString stringWithFormat:@"%d",self.pIndex];
    paramDict[@"CurrentUserLocalId"] = USERID;
    
    [self.viewModel getUserTopicList:paramDict contentArr:^(NSMutableArray *contentArr) {
        if (contentArr){
            if (isHead){
                [self.contentArray removeAllObjects];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [self.contentArray addObjectsFromArray:contentArr];
                
                [self.tableView reloadData];
                //                if (weakSelf.contentArray.count){
                //                    [weakSelf starAnimationWithTableView:self.tableView];
                //                }
                if (contentArr.count < 20){
                    self.tableView.mj_footer.hidden = YES;
                }
            });
        }
    }];
}

#pragma mark 获取数据
- (void)creatDefaultParam {
    // 请求数据
    [self.param setObject:[NSString stringWithFormat:@"%d", 10] forKey:@"PageSize"];
    [self.param setObject:USERID forKey:@"CurrentUserLocalId"];
    
    [self addRefresh];
    [self.tableView.mj_header beginRefreshing];
}

- (void)addRefresh {
    // 添加头部刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        isHeader = YES;
        self.pIndex = 0;
        [self.param setObject:[NSString stringWithFormat:@"%d", self.pIndex] forKey:@"PageIndex"];
        [self requestListData];
    }];
    // 添加尾部加载控件(上提加载)
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        isHeader = NO;
        self.pIndex += 1;
        [self.param setObject:[NSString stringWithFormat:@"%d", self.pIndex] forKey:@"PageIndex"];
        [self requestListData];
    }];
}

- (void)requestListData {
    
    if (isHeader == YES) {
        [self.contentArray removeAllObjects];
    }
    
    YTKApi *api = [YTKApi apiGetWithUrl:@"UserInfo/Get_GetUserTopicList" para:self.param];
    [api getSuccessToken:^() {
        api.foceNoTocken = NO;
        [api setRequestSerializerType:YTKRequestSerializerTypeJSON];
        [api startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
            
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer endRefreshing];
            
            NSDictionary *dict = request.responseJSONObject;
            
            if ([dict[@"CodeStatus"] integerValue] == 20000) {
                
                NSArray *temparr = [NSArray modelArrayWithClass:[HRFunChatModel class] json:dict[@"BodyContent"]];
                
                [self.contentArray addObjectsFromArray:temparr];
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.tableView reloadData];
                });
            }
            
        } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer endRefreshing];
        }];
    }];
    
}


- (NSString *)getCurrentTime {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYY-MM-dd hh:mm:ss"];
    
    return [formatter stringFromDate:[NSDate date]];
}


- (void)reloadChatSelfNotifi{
    [self getFunChatContent];
//    [self creatDefaultParam];
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [self.currentCell.streamer pause];
    [self.currentCell.voicImageView stopAnimating];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
